using System;
using System.Data;
using System.Text;
using System.Windows.Forms;
using ctsu.Admin.BusLogic;
//using Chb.ctsu.Data;

using ctsu.Data;

namespace ctsu.Admin.Forms
{
	/// <summary>
	/// Summary description for QuerySpidTestDlg.
	/// </summary>
	public class QuerySpidTestDlg : System.Windows.Forms.Form
	{
		#region members
		public string InventoryLocation;

		private int _protocol;
		private int _test;
		private int _patient;

		#endregion members

		#region windows controls
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.Label label3;
		private System.Windows.Forms.ComboBox Tests;
		public System.Windows.Forms.ListView lvw;
		private System.Windows.Forms.ListBox Results;
		private System.Windows.Forms.Label label6;
		private System.Windows.Forms.ComboBox Patients;
		private System.Windows.Forms.ColumnHeader columnHeader1;
		private System.Windows.Forms.ColumnHeader columnHeader2;
		private System.Windows.Forms.ColumnHeader columnHeader3;
		private System.Windows.Forms.ColumnHeader columnHeader4;
		private System.Windows.Forms.ColumnHeader columnHeader5;
		private System.Windows.Forms.Button btnCancel;
		private System.Windows.Forms.Button btnOK;
		private System.Windows.Forms.GroupBox groupBox1;
		private System.Windows.Forms.Button RunQuery;
		private System.Windows.Forms.Label label4;
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.ComboBox Protocols;

		private System.ComponentModel.Container components = null;
		#endregion windows controls

		public QuerySpidTestDlg(int protocol, int test, int patient)
		{
			InitializeComponent();
			this._protocol = protocol;
			this._test = test;
			this._patient = patient;
			this.InventoryLocation = "";
		}

		protected override void Dispose(bool disposing)
		{
			if (disposing)
			{
				if (components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose(disposing);
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.Protocols = new System.Windows.Forms.ComboBox();
			this.label2 = new System.Windows.Forms.Label();
			this.label3 = new System.Windows.Forms.Label();
			this.Tests = new System.Windows.Forms.ComboBox();
			this.lvw = new System.Windows.Forms.ListView();
			this.columnHeader1 = new System.Windows.Forms.ColumnHeader();
			this.columnHeader2 = new System.Windows.Forms.ColumnHeader();
			this.columnHeader3 = new System.Windows.Forms.ColumnHeader();
			this.columnHeader4 = new System.Windows.Forms.ColumnHeader();
			this.columnHeader5 = new System.Windows.Forms.ColumnHeader();
			this.Results = new System.Windows.Forms.ListBox();
			this.label6 = new System.Windows.Forms.Label();
			this.Patients = new System.Windows.Forms.ComboBox();
			this.btnCancel = new System.Windows.Forms.Button();
			this.btnOK = new System.Windows.Forms.Button();
			this.groupBox1 = new System.Windows.Forms.GroupBox();
			this.RunQuery = new System.Windows.Forms.Button();
			this.label4 = new System.Windows.Forms.Label();
			this.label1 = new System.Windows.Forms.Label();
			this.groupBox1.SuspendLayout();
			this.SuspendLayout();
			// 
			// Protocols
			// 
			this.Protocols.Location = new System.Drawing.Point(8, 32);
			this.Protocols.Name = "Protocols";
			this.Protocols.Size = new System.Drawing.Size(121, 21);
			this.Protocols.TabIndex = 1;
			// 
			// label2
			// 
			this.label2.Location = new System.Drawing.Point(8, 16);
			this.label2.Name = "label2";
			this.label2.Size = new System.Drawing.Size(88, 16);
			this.label2.TabIndex = 2;
			this.label2.Text = "Protocol";
			// 
			// label3
			// 
			this.label3.Location = new System.Drawing.Point(144, 16);
			this.label3.Name = "label3";
			this.label3.Size = new System.Drawing.Size(88, 16);
			this.label3.TabIndex = 4;
			this.label3.Text = "Test Type";
			// 
			// Tests
			// 
			this.Tests.Location = new System.Drawing.Point(144, 32);
			this.Tests.Name = "Tests";
			this.Tests.Size = new System.Drawing.Size(176, 21);
			this.Tests.TabIndex = 3;
			// 
			// lvw
			// 
			this.lvw.Activation = System.Windows.Forms.ItemActivation.TwoClick;
			this.lvw.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
				| System.Windows.Forms.AnchorStyles.Left)
				| System.Windows.Forms.AnchorStyles.Right)));
			this.lvw.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
																				  this.columnHeader1,
																				  this.columnHeader2,
																				  this.columnHeader3,
																				  this.columnHeader4,
																				  this.columnHeader5});
			this.lvw.FullRowSelect = true;
			this.lvw.GridLines = true;
			this.lvw.HideSelection = false;
			this.lvw.Location = new System.Drawing.Point(152, 96);
			this.lvw.MultiSelect = false;
			this.lvw.Name = "lvw";
			this.lvw.Size = new System.Drawing.Size(464, 237);
			this.lvw.TabIndex = 26;
			this.lvw.View = System.Windows.Forms.View.Details;
			this.lvw.ItemActivate += new System.EventHandler(this.btnOK_Click);
			// 
			// columnHeader1
			// 
			this.columnHeader1.Text = "Test ID";
			this.columnHeader1.Width = 48;
			// 
			// columnHeader2
			// 
			this.columnHeader2.Text = "Protocol";
			this.columnHeader2.Width = 41;
			// 
			// columnHeader3
			// 
			this.columnHeader3.Text = "Patient";
			this.columnHeader3.Width = 86;
			// 
			// columnHeader4
			// 
			this.columnHeader4.Text = "Test Type";
			this.columnHeader4.Width = 105;
			// 
			// columnHeader5
			// 
			this.columnHeader5.Text = "Location";
			this.columnHeader5.Width = 135;
			// 
			// Results
			// 
			this.Results.Location = new System.Drawing.Point(8, 96);
			this.Results.Name = "Results";
			this.Results.Size = new System.Drawing.Size(128, 238);
			this.Results.TabIndex = 28;
			this.Results.SelectedIndexChanged += new System.EventHandler(this.Results_SelectedIndexChanged);
			// 
			// label6
			// 
			this.label6.Location = new System.Drawing.Point(336, 16);
			this.label6.Name = "label6";
			this.label6.Size = new System.Drawing.Size(72, 16);
			this.label6.TabIndex = 30;
			this.label6.Text = "Patient";
			// 
			// Patients
			// 
			this.Patients.Location = new System.Drawing.Point(336, 32);
			this.Patients.Name = "Patients";
			this.Patients.Size = new System.Drawing.Size(176, 21);
			this.Patients.TabIndex = 3;
			// 
			// btnCancel
			// 
			this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
			this.btnCancel.Location = new System.Drawing.Point(360, 344);
			this.btnCancel.Name = "btnCancel";
			this.btnCancel.TabIndex = 32;
			this.btnCancel.Text = "&Cancel";
			this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
			// 
			// btnOK
			// 
			this.btnOK.Location = new System.Drawing.Point(272, 344);
			this.btnOK.Name = "btnOK";
			this.btnOK.TabIndex = 31;
			this.btnOK.Text = "&OK";
			this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
			// 
			// groupBox1
			// 
			this.groupBox1.Controls.Add(this.RunQuery);
			this.groupBox1.Controls.Add(this.label2);
			this.groupBox1.Controls.Add(this.label3);
			this.groupBox1.Controls.Add(this.Tests);
			this.groupBox1.Controls.Add(this.Protocols);
			this.groupBox1.Controls.Add(this.Patients);
			this.groupBox1.Controls.Add(this.label6);
			this.groupBox1.Location = new System.Drawing.Point(8, 8);
			this.groupBox1.Name = "groupBox1";
			this.groupBox1.Size = new System.Drawing.Size(608, 64);
			this.groupBox1.TabIndex = 0;
			this.groupBox1.TabStop = false;
			this.groupBox1.Text = "Search Criteria";
			// 
			// RunQuery
			// 
			this.RunQuery.Location = new System.Drawing.Point(520, 32);
			this.RunQuery.Name = "RunQuery";
			this.RunQuery.TabIndex = 4;
			this.RunQuery.Text = "&Run Query";
			this.RunQuery.Click += new System.EventHandler(this.RunQuery_Click);
			// 
			// label4
			// 
			this.label4.Location = new System.Drawing.Point(8, 80);
			this.label4.Name = "label4";
			this.label4.Size = new System.Drawing.Size(141, 16);
			this.label4.TabIndex = 47;
			this.label4.Text = "Location (search results):";
			// 
			// label1
			// 
			this.label1.Location = new System.Drawing.Point(152, 80);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(160, 16);
			this.label1.TabIndex = 50;
			this.label1.Text = "Contents of selected location:";
			// 
			// QuerySpidTestDlg
			// 
			this.AcceptButton = this.btnOK;
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.CancelButton = this.btnCancel;
			this.ClientSize = new System.Drawing.Size(632, 374);
			this.Controls.Add(this.label1);
			this.Controls.Add(this.groupBox1);
			this.Controls.Add(this.btnCancel);
			this.Controls.Add(this.btnOK);
			this.Controls.Add(this.Results);
			this.Controls.Add(this.lvw);
			this.Controls.Add(this.label4);
			this.Name = "QuerySpidTestDlg";
			this.Text = "QuerySpidTestDlg";
			this.Load += new System.EventHandler(this.QuerySpidTestDlg_Load);
			this.groupBox1.ResumeLayout(false);
			this.ResumeLayout(false);

		}
		#endregion

		private void QuerySpidTestDlg_Load(object sender, System.EventArgs e)
		{
			FillSpidList();
			if (this._protocol != -1)
				Protocols.Text = this._protocol.ToString();

			FillPatientList();
			if (this._patient > 0)
			{
				//get the patient info
				string message = "";
				PatientInfo pi = CoreLabUtils.GetPatientInfo(_patient, out message);
				Patients.Text = pi.MRN;
			}

			FillTestList();
			if (this._test > -1)
				Tests.SelectedIndex = GetTestIndex(_test);
			if (this._protocol > 0)
				GetResults();

		}

		private void FillSpidList()
		{
			StringBuilder sb = new StringBuilder();
			string sql = "";

			Protocols.Items.Clear();

			sql = "SELECT DISTINCT d.Protocol " +
				" FROM TestSamples t, DrawSamples d " +
				" WHERE t.Location Is Not Null " +
				" AND t.DrawSample = d.ID ";

			//SqlConnection conn = LoginForm.GetSqlConnection();
			IDataReader reader = null;
			try
			{
				reader = DataAccess.GetDataReader(sql);

				Protocols.BeginUpdate();
				Protocols.Items.Add("");
				while (reader.Read())
				{
					Protocols.Items.Add(reader.GetInt32(0).ToString());
				}
			}
			catch (Exception ex)
			{
				sb.Append("Could not retrieve Protocols for Protocol List!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this, sb.ToString(), "Fill Protocol List Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
			finally
			{
				if (reader != null)
				{
					if (!reader.IsClosed)
						reader.Close();
				}
				//if(conn != null)
				//    conn.Dispose();
				Protocols.EndUpdate();
			}
		}

		private void FillTestList()
		{
			StringBuilder sb = new StringBuilder();
			string sql = "";

			Tests.Items.Clear();

			sql = "SELECT DISTINCT tt.Display, t.TestType " +
				" From TestType_L tt, TestSamples t, DrawSamples d " +
				" WHERE t.Location Is Not Null " +
				" AND t.DrawSample = d.ID " +
				" AND t.TestType = tt.ID ";

			NameVal nv = null;

			//SqlConnection conn = LoginForm.GetSqlConnection();
			IDataReader reader = null;
			try
			{
				reader = DataAccess.GetDataReader(sql.ToString());

				Tests.BeginUpdate();
				Tests.Items.Add("");
				while (reader.Read())
				{
					nv = new NameVal(reader.GetInt32(1), reader.GetString(0));
					Tests.Items.Add(nv);
				}
			}
			catch (Exception ex)
			{
				sb.Append("Could not retrieve tests for Test Type List!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this, sb.ToString(), "Fill Test Type List Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
			finally
			{
				if (reader != null)
				{
					if (!reader.IsClosed)
						reader.Close();
				}
				//if(conn != null)
				//    conn.Dispose();	
				Tests.EndUpdate();
			}
		}

		private void FillPatientList()
		{
			string message = "";
			StringBuilder sb = new StringBuilder();
			string sql = "";

			Patients.Items.Clear();

			sql = "SELECT DISTINCT d.Patient " +
				" From TestSamples t, DrawSamples d " +
				" WHERE t.Location Is Not Null " +
				" AND t.DrawSample = d.ID";

			//SqlConnection conn = LoginForm.GetSqlConnection();
			IDataReader reader = null;
			try
			{
				reader = DataAccess.GetDataReader(sql.ToString());

				Patients.BeginUpdate();
				Patients.Items.Add("");
				PatientInfo pi = null;
				while (reader.Read())
				{
					int patID = reader.GetInt32(0);
					pi = CoreLabUtils.GetPatientInfo(patID, out message);
					NameVal nv = new NameVal(patID, pi.MRN);
					Patients.Items.Add(nv);
				}
			}
			catch (Exception ex)
			{
				sb.Append("Could not retrieve patients for Patient List!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this, sb.ToString(), "Fill Patient List Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
			finally
			{
				if (reader != null)
				{
					if (!reader.IsClosed)
						reader.Close();
				}
				//if(conn != null)
				//    conn.Dispose();
				Patients.EndUpdate();
			}
		}

		private int GetTestIndex(int _test)
		{
			for (int i = 1; i < Tests.Items.Count; i++)
			{
				NameVal nv = (NameVal)Tests.Items[i];
				if (nv.Val == _test)
					return i;
			}
			return -1;
		}

		private void GetResults()
		{
			StringBuilder sb = new StringBuilder();
			StringBuilder sql = new StringBuilder();
			int protocol = 0;
			int testID = 0;
			int patient = 0;
			NameVal nv = null;

			Results.BeginUpdate();
			Results.Items.Clear();
			lvw.Items.Clear();

			if (Protocols.SelectedIndex < 1 && Tests.SelectedIndex < 1 && Patients.SelectedIndex < 1)
			{
				return;
			}
			else if (Protocols.SelectedIndex > 0 && Tests.SelectedIndex < 1 && Patients.SelectedIndex < 1)
			{
				protocol = Convert.ToInt32(Protocols.Text);
				sql.Append("SELECT DISTINCT t.Location " +
					" From TestSamples t, DrawSamples d " +
					" WHERE t.Location Is Not Null " +
					" AND t.DrawSample = d.ID " +
					" AND d.Protocol=" + protocol);
			}
			else if (Protocols.SelectedIndex > 0 && Tests.SelectedIndex > 0 && Patients.SelectedIndex < 1)
			{
				protocol = Convert.ToInt32(Protocols.Text);
				testID = ((NameVal)Tests.SelectedItem).Val;
				sql.Append("SELECT DISTINCT t.Location " +
					" From TestSamples t, DrawSamples d " +
					" WHERE t.Location Is Not Null " +
					" AND t.DrawSample = d.ID " +
					" AND t.TestType = " + testID +
					" AND d.Protocol=" + protocol);
			}
			else if (Protocols.SelectedIndex > 0 && Tests.SelectedIndex < 1 && Patients.SelectedIndex > 0)
			{
				nv = (NameVal)Patients.SelectedItem;
				patient = nv.Val;
				protocol = Convert.ToInt32(Protocols.Text);
				sql.Append("SELECT DISTINCT t.Location " +
					" From TestSamples t, DrawSamples d " +
					" WHERE t.Location Is Not Null " +
					" AND t.DrawSample = d.ID " +
					" AND d.Protocol=" + protocol +
					" AND d.Patient = " + patient);
			}
			else if (Protocols.SelectedIndex < 1 && Tests.SelectedIndex > 0 && Patients.SelectedIndex < 1)
			{
				testID = ((NameVal)Tests.SelectedItem).Val;
				sql.Append("SELECT DISTINCT t.Location " +
					" From TestSamples t, DrawSamples d " +
					" WHERE t.Location Is Not Null " +
					" AND t.DrawSample = d.ID " +
					" AND t.TestType = " + testID);
			}
			else if (Protocols.SelectedIndex < 1 && Tests.SelectedIndex > 0 && Patients.SelectedIndex > 0)
			{
				nv = (NameVal)Patients.SelectedItem;
				patient = nv.Val;
				testID = ((NameVal)Tests.SelectedItem).Val;
				sql.Append("SELECT DISTINCT t.Location " +
					" From TestSamples t, DrawSamples d " +
					" WHERE t.Location Is Not Null " +
					" AND t.DrawSample = d.ID " +
					" AND t.TestType = " + testID +
					" AND d.Patient = " + patient);
			}
			else if (Protocols.SelectedIndex < 1 && Tests.SelectedIndex < 1 && Patients.SelectedIndex > 0)
			{
				nv = (NameVal)Patients.SelectedItem;
				patient = nv.Val;
				sql.Append("SELECT DISTINCT t.Location " +
					" From TestSamples t, DrawSamples d " +
					" WHERE t.Location Is Not Null " +
					" AND t.DrawSample = d.ID " +
					" AND d.Patient = " + patient);
			}
			else if (Protocols.SelectedIndex > 0 && Tests.SelectedIndex > 0 && Patients.SelectedIndex > 0)
			{
				protocol = Convert.ToInt32(Protocols.Text);
				nv = (NameVal)Patients.SelectedItem;
				patient = nv.Val;
				testID = ((NameVal)Tests.SelectedItem).Val;
				sql.Append("SELECT DISTINCT t.Location " +
					" From TestSamples t, DrawSamples d " +
					" WHERE t.Location Is Not Null " +
					" AND t.DrawSample = d.ID " +
					" AND t.TestType = " + testID +
					" AND d.Protocol=" + protocol +
					" AND d.Patient = " + patient);
			}

			//SqlConnection conn = LoginForm.GetSqlConnection();
			IDataReader reader = null;
			try
			{
				reader = DataAccess.GetDataReader(sql.ToString());

				while (reader.Read())
				{
					Results.Items.Add(reader.GetString(0));
				}
			}
			catch (Exception ex)
			{
				sb.Append("Could not retrieve results!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this, sb.ToString(), "Fill Results List Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
			finally
			{
				if (reader != null)
				{
					if (!reader.IsClosed)
						reader.Close();
				}
				//if(conn != null)
				//    conn.Dispose();
				Results.EndUpdate();
			}
		}

		private void Results_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			Cursor.Current = Cursors.WaitCursor;
			GetContents();
		}

		private void GetContents()
		{
			StringBuilder sb = new StringBuilder();
			string sql = "SELECT DISTINCT t.ID, d.Protocol, d.Patient, " +
				" tt.Display, t.Location " +
				" FROM TestSamples t, DrawSamples d, TestType_L tt " +
				" WHERE t.Location = '" + (string)Results.SelectedItem + "' " +
				" AND t.DrawSample = d.ID " +
				" AND t.TestType = tt.ID";


			lvw.BeginUpdate();
			lvw.Items.Clear();

			string message = "";
			PatientInfo pi = null;

			//SqlConnection conn = LoginForm.GetSqlConnection();
			IDataReader reader = null;
			int patient = 0;
			try
			{
				reader = DataAccess.GetDataReader(sql);
				while (reader.Read())
				{
					ListViewItem lvi = new ListViewItem(reader.GetInt32(0).ToString());
					lvi.SubItems.Add(reader.GetInt32(1).ToString());
					patient = reader.GetInt32(2);
					pi = CoreLabUtils.GetPatientInfo(patient, out message);
					lvi.SubItems.Add(pi.MRN);
					lvi.SubItems.Add(reader.GetString(3));
					lvi.SubItems.Add(reader.GetString(4));
					lvw.Items.Add(lvi);
				}
			}
			catch (Exception ex)
			{
				sb.Append("Could not retrieve sample!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this, sb.ToString(), "Retrieve Sample Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			finally
			{
				if (reader != null)
				{
					if (!reader.IsClosed)
						reader.Close();
				}
				//if(conn != null)
				//    conn.Dispose();
				lvw.EndUpdate();
			}
		}

		private void btnCancel_Click(object sender, System.EventArgs e)
		{
			this.Close();
		}

		private void btnOK_Click(object sender, System.EventArgs e)
		{
			if (lvw.SelectedItems.Count > 0)
				this.InventoryLocation = lvw.SelectedItems[0].SubItems[4].Text;
			this.Close();
		}

		private void RunQuery_Click(object sender, System.EventArgs e)
		{
			RunQuery.Enabled = false;
			Cursor.Current = Cursors.WaitCursor;
			this.GetResults();
			RunQuery.Enabled = true;
		}



	}
}
